<!-- 项目展示预览页面 -->
<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <PageHeader title="项目简介" :showBack="true" />

    <!-- 预览内容 -->
    <view class="px-6 mt-4">
      <!-- 加载状态 -->
      <view v-if="loading" class="flex justify-center items-center py-20">
        <text class="text-[28rpx] text-gray-500">加载中...</text>
      </view>
      
      <!-- 项目内容 -->
      <template v-else>
      <!-- 项目图片 -->
      <view class="bg-white rounded-2xl shadow-sm overflow-hidden mb-6">
        <swiper 
          class="w-full h-[500rpx]" 
          :indicator-dots="true"
          :autoplay="false"
          indicator-color="rgba(255,255,255,0.5)"
          indicator-active-color="#165DFF"
        >
          <swiper-item v-for="(image, index) in previewData.images" :key="index">
            <image 
              :src="image" 
              class="w-full h-full object-cover cursor-pointer"
              mode="aspectFill"
              @click="previewImage(index)"
            />
          </swiper-item>
        </swiper>
      </view>

        <!-- 项目标题 -->
        <view class="mb-6">
          <text class="text-[36rpx] font-bold text-gray-900 leading-relaxed">{{ previewData.title }}</text>
        </view>

        <!-- 项目描述 -->
        <view class="mb-6">
          <text 
            class="text-[28rpx] text-gray-700 leading-relaxed"
            :class="{ 'line-clamp-3': !isDescriptionExpanded }"
          >
            {{ previewData.description }}
          </text>
          <!-- 展开/收起按钮 -->
          <view 
            v-if="previewData.description && previewData.description.length > 100"
            class="mt-3 flex-center px-[20rpx]"
          >
            <nut-button 
              type="primary" 
              size="small" 
              plain
              @click="toggleDescription"
            >
            <template #icon>
                <IconFont 
                  name="triangle-down" 
                  size="16" 
                  class="mr-1" 
                  :class="{ 'rotate-180': isDescriptionExpanded }"
                />
              </template>
              {{ isDescriptionExpanded ? '收起' : '展开' }}
            </nut-button>
          </view>
        </view>

      <!-- 项目信息 -->
      <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">


        <!-- 联系信息 -->
        <view class="mb-6 flex items-center">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="liaotian" size="18" class="text-blue-600 mr-3" />
          <text class="text-[28rpx] text-gray-700">{{ previewData.contact }}</text>
        </view>

        <!-- 服务区域 -->
        <view class="flex items-center">
          <IconFont name="location" size="18" class="text-blue-600 mr-3" />
          <text class="text-[28rpx] text-gray-700">{{ previewData.serviceArea }}</text>
        </view>
      </view>

      <!-- 任务发布方 -->
      <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
        <view class="flex items-center text-[36rpx] font-bold mb-4">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="service-provider_fill" class="mr-3 text-blue-600" size="26" />
          <text>项目发布方</text>
        </view>
        <view class="publisher-card bg-gray-50 rounded-2xl p-4 border border-gray-200">
          <view class="publisher-header flex items-center justify-between">
            <text class="publisher-name text-[32rpx] font-bold">{{ previewData.publisherName || '未知发布者' }}</text>
            <nut-button type="success" size="small" @click="contactPublisher">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="xiaoxi" class="mr-2 align-middle" size="16" />
              联系发布方
            </nut-button>
          </view>
        </view>
      </view>

      <!-- 平台提示 -->
      <view class="bg-blue-50 border-l-4 border-blue-500 rounded-2xl p-6 mb-8">
        <view class="flex items-center mb-4">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="xinxiinfo21" class="text-blue-600 mr-3" size="20" />
          <text class="text-[32rpx] font-bold text-blue-900">平台提示</text>
        </view>
        <view class="text-[28rpx] leading-relaxed text-blue-800">
          <text class="block">1. 项目展示已通过平台审核，信息真实可靠</text>
          <text class="block mt-3">2. 如有疑问可直接联系项目发布方进行沟通</text>
          <text class="block mt-3">3. 平台提供安全保障，保护双方合法权益</text>
          <text class="block mt-3">4. 如有纠纷可申请平台仲裁处理</text>
        </view>
      </view>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'
import Taro from '@tarojs/taro'
import PageHeader from '@/components/PageHeader.vue'
import { post } from '@/utils/request'
import { useUserStore } from '@/store/user'

/**
 * 预览数据类型定义
 */
interface PreviewData {
  title: string
  description: string
  images: string[]
  contact: string
  serviceArea: string
  regionLevel: string
  fee: string
  publisherName: string
  publisherId: number
}

// 响应式数据
const loading = ref(false)
const isDescriptionExpanded = ref(false)
const previewData = ref<PreviewData>({
  title: '',
  description: '',
  images: [],
  contact: '',
  serviceArea: '',
  regionLevel: 'city',
  fee: '1',
  publisherName: '',
  publisherId: 0
})


/**
 * 切换描述展开状态
 */
const toggleDescription = () => {
  isDescriptionExpanded.value = !isDescriptionExpanded.value
}

/**
 * 预览图片
 */
const previewImage = (current: number) => {
  if (previewData.value.images && previewData.value.images.length > 0) {
    Taro.previewImage({
      current: previewData.value.images[current],
      urls: previewData.value.images
    })
  }
}

/**
 * 获取图片列表
 * @param pics 图片字符串，用逗号分隔
 */
const getImageList = (pics: string) => {
  if (!pics) return ['http://www.dzgktf.com/templets/default/images/wtyt.jpg']
  const images = pics.split(',').filter(pic => pic.trim())
  return images.length > 0 ? images : ['http://www.dzgktf.com/templets/default/images/wtyt.jpg']
}

/**
 * 获取范围类型文本
 * @param rangeType 范围类型
 */
const getRangeTypeText = (rangeType: number) => {
  const rangeMap: { [key: number]: string } = {
    0: '全国',
    1: '省级',
    2: '市级'
  }
  return rangeMap[rangeType] || '未知'
}

/**
 * 联系发布方
 */
const contactPublisher = () => {
  // 检查是否是发布者本人
  const userStore = useUserStore()
  if (previewData.value.publisherId === userStore.userInfo.id) {
    Taro.showToast({
      title: '不能与自己聊天',
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 跳转到聊天页面
  Taro.navigateTo({
    url: `/pages/message/chat?userId=${previewData.value.publisherId}&userName=${previewData.value.publisherName}`
  })
}

/**
 * 获取项目详情
 */
const fetchProjectDetail = async () => {
  try {
    loading.value = true
    
    // 获取路由参数中的id
    const router = Taro.getCurrentInstance().router
    const id = router?.params?.id
    
    if (!id) {
      Taro.showToast({
        title: '缺少项目ID',
        icon: 'error'
      })
      return
    }
    
    // 调用接口获取项目详情
    const res = await post('/groupTypes/getById', { id })
    
    if (res.code === 0 && res.data && res.data.columns) {
      const data = res.data.columns
      // 将详情数据映射到预览数据
      previewData.value = {
        title: data.title || '未知项目',
        description: data.content || '暂无描述',
        images: getImageList(data.pics || ''),
        contact: data.contact || '暂无联系方式',
        serviceArea: data.address || '未选择区域',
        regionLevel: data.range_type === '0' ? 'nation' : data.range_type === '1' ? 'province' : 'city',
        fee: data.release_fee?.toString() || '1',
        publisherName: data.publisherName || '未知发布者',
        publisherId: data.member_id || 0
      }
    } else {
      Taro.showToast({
        title: '获取项目详情失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    Taro.showToast({
      title: '网络错误，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(() => {
  // 调用接口获取项目详情
  fetchProjectDetail()
})
</script>

<style scoped>
/* 文本截断样式 */
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
